<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JWT 认证演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }

        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        input {
            display: block;
            margin: 10px 0;
            padding: 8px;
            width: 200px;
        }

        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        button:hover {
            background-color: #45a049;
        }

        .message {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }

        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }

        .error {
            background-color: #f2dede;
            color: #a94442;
        }
    </style>
</head>
<body>
<h1>JWT 认证演示</h1>

<div class="section">
    <h2>登录</h2>
    <input type="text" id="username" placeholder="用户名" value="admin">
    <input type="password" id="password" placeholder="密码" value="123456">
    <button onclick="login()">登录</button>
    <div id="loginMessage" class="message"></div>
</div>

<div class="section">
    <h2>用户信息</h2>
    <button onclick="getUserInfo()">获取我的信息</button>
    <div id="userInfo" class="message"></div>
</div>

<div class="section">
    <h2>CORS 测试</h2>
    <button onclick="testCors()">测试CORS配置</button>
    <div id="corsTest" class="message"></div>
</div>

<script>
    const API_BASE_URL = 'http://localhost:9000';
    const TOKEN_KEY = 'jwt_token';

    // 显示消息
    function showMessage(elementId, message, isError = false) {
        const element = document.getElementById(elementId);
        element.textContent = message;
        element.className = isError ? 'message error' : 'message success';
    }

    // 登录功能
    async function login() {
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();

        if (!username || !password) {
            showMessage('loginMessage', '请输入用户名和密码', true);
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });

            if (!response.ok) {
                const error = await response.text();
                throw new Error(error || '登录失败');
            }

            const token = await response.text();
            localStorage.setItem(TOKEN_KEY, token);
            showMessage('loginMessage', '登录成功！Token 已保存');
        } catch (error) {
            showMessage('loginMessage', `登录失败: ${error.message}`, true);
            console.error('登录错误:', error);
        }
    }

    // 获取用户信息
    async function getUserInfo() {
        const token = localStorage.getItem(TOKEN_KEY);

        if (!token) {
            showMessage('userInfo', '请先登录！', true);
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/auth/me`, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                }
            });

            if (!response.ok) {
                const error = await response.text();
                throw new Error(error || '获取用户信息失败');
            }

            const username = await response.text();
            showMessage('userInfo', `当前用户: ${username}`);
        } catch (error) {
            showMessage('userInfo', `获取用户信息失败: ${error.message}`, true);
            console.error('获取用户信息错误:', error);

            // 如果Token无效，清除本地存储
            if (error.message.includes('Unauthorized') || error.message.includes('Invalid')) {
                localStorage.removeItem(TOKEN_KEY);
            }
        }
    }

    // 测试CORS配置
    async function testCors() {
        try {
            // 测试带Authorization头的请求（如果已登录）
            const token = localStorage.getItem(TOKEN_KEY);
            if (token) {
                const authResponse = await fetch(`${API_BASE_URL}/auth/test`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (!authResponse.ok) {
                    throw new Error('带Token的CORS请求失败');
                }
                showMessage('corsTest', `CORS测试成功`);
            }
        } catch (error) {
            showMessage('corsTest', `CORS测试失败: ${error.message}`, true);
            console.error('CORS测试错误:', error);
        }
    }
</script>
</body>
</html>